//
//  CartViewController.m
//  WuJieLive
//
//  Created by iMac on 2017/10/20.
//  Copyright © 2017年 zhk. All rights reserved.
//

#import "CartViewController.h"
#import "EmptyView.h"
#import "CartCell.h"
#import "ToolBar.h"
#import "OrderDetailModel.h"
#import "ConfirmOrderController.h"
#import "CartModel.h"
#import "AddressCell.h"

@interface CartViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic , strong) UITableView * tableview;
@property (nonatomic , strong) NSMutableArray * dataArray;
@property (nonatomic , assign) CGFloat totalMonry;
@property (nonatomic , strong) ToolBar * toolBar ;
@property (nonatomic , strong) EmptyView * emptyView;
@property (nonatomic , assign) NSInteger index;

@end

@implementation CartViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestData) name:@"reload" object:nil];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.hidesBottomBarWhenPushed=NO;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.needLeftBtn) {
        self.leftBtn.hidden = NO;
    }else{
        self.leftBtn.hidden = YES;
    }
}

- (void)setNavi
{
    self.title = @"购物车";
}

-(void)rightBtnAction:(UIButton *)sender
{
    //设置编辑状态
    if (self.tableview.editing == YES) {
        [sender setTitle:@"编辑" forState:(UIControlStateNormal)];
        [self.tableview setEditing:NO animated:YES];
        [self.toolBar.settleBtn setTitle:@"结算" forState:(UIControlStateNormal)];
    }else
    {
        [sender setTitle:@"取消" forState:(UIControlStateNormal)];
        [self.tableview setEditing:YES animated:YES];
        [self.toolBar.settleBtn setTitle:@"删除" forState:(UIControlStateNormal)];
    }
    self.toolBar.addUpLabel.hidden = self.tableview.editing;
    self.toolBar.fareLabel.hidden = self.tableview.editing;
    self.toolBar.pirceLabel.hidden = self.tableview.editing;
}

- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

// 初始底部工具栏
- (void)initToolBar
{
    [self.toolBar.settleBtn setTitle:@"结算" forState:(UIControlStateNormal)];
    self.toolBar.selectAllBtn.selected = NO;
    self.toolBar.pirceLabel.text = [NSString stringWithFormat:@"¥:0.00"];
    self.toolBar.addUpLabel.hidden = NO;
    self.toolBar.fareLabel.hidden = NO;
    self.toolBar.pirceLabel.hidden = NO;
    [self.rightBtn setTitle:@"编辑" forState:(UIControlStateNormal)];
    __weak typeof(self) weakSelf = self;
    self.toolBar.selectAllBlock = ^(BOOL isSelectedAll) {
        if (isSelectedAll) {
            weakSelf.totalMonry = 0;
            for (int i = 0 ; i < weakSelf.dataArray.count; i ++) {
                CartModel * model = weakSelf.dataArray[i];
                model.isSelected = YES;
                weakSelf.totalMonry = [model.price_coupon floatValue] * [model.goods_number integerValue] + weakSelf.totalMonry;
            }
            weakSelf.toolBar.pirceLabel.text = [NSString stringWithFormat:@"%.2f",weakSelf.totalMonry];
        }else
        {
            for (int i = 0 ; i < weakSelf.dataArray.count; i ++) {
                CartModel * model = weakSelf.dataArray[i];
                model.isSelected = NO;
            }
            weakSelf.totalMonry = 0.00;
            weakSelf.toolBar.pirceLabel.text = [NSString stringWithFormat:@"%.2f",weakSelf.totalMonry];
        }
        [weakSelf.tableview reloadData];
    };
    
    self.toolBar.settleBlock = ^(UIButton *sender) {
        if ([sender.titleLabel.text isEqualToString:@"删除"]) {
            [weakSelf deleteGoods];
        }else
        {
            for (CartModel * model in weakSelf.dataArray) {
                if (model.isSelected) {
                    [weakSelf settle];
                    return ;
                }
            }
        }
    };
    
    [self.toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.height.offset(50);
    }];
}

- (void)deleteGoods
{
    NSMutableString *  string = [NSMutableString string];
    NSMutableArray * array = [NSMutableArray array];
    for (int i = 0; i < self.dataArray.count; i ++) {
        CartModel * model = self.dataArray[i];
        if (model.isSelected) {
            [array addObject:model];
        }
    }
    for (int i = 0 ; i < array.count; i ++) {
        CartModel * model = array[i];
        if (i == 0) {
            [string appendString:model.cart_id];
        }else
        {
            [string appendString:[NSString stringWithFormat:@",%@",model.cart_id]];
        }
    }
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSDictionary * dict = @{@"token":self.userToken,@"cart_ids":string};
    [HTTPTool POSTForm:[NSString stringWithFormat:@"%@cart/delete-cart",BaseUrl] para:dict success:^(BOOL isSuccess, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (isSuccess) {
            for (int i = 0; i < array.count; i ++) {
                [self.dataArray removeObject:array[i]];
            }
            self.tableview.editing = NO;
            [self initToolBar];
            [self.tableview reloadData];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}
#pragma mark 结算
- (void)settle
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableString *  string = [NSMutableString string];
    NSMutableArray * array = [NSMutableArray array];
    for (int i = 0; i < self.dataArray.count; i ++) {
        CartModel * model = self.dataArray[i];
        if (model.isSelected) {
            [array addObject:model];
        }
    }
    for (int i = 0 ; i < array.count; i ++) {
        CartModel * model = array[i];
        if (i == 0) {
            [string appendString:model.cart_id];
        }else
        {
            [string appendString:[NSString stringWithFormat:@",%@",model.cart_id]];
        }
    }
    __weak typeof (self) weakSelf = self;
    NSDictionary * dict = @{@"token":self.userToken,@"cart_ids":string};
    [HTTPTool POSTForm:[NSString stringWithFormat:@"%@cart/cart-goods-settlement",BaseUrl] para:dict success:^(BOOL isSuccess, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (isSuccess) {
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            NSDictionary * dic = @{@"token":self.userToken,@"cart_ids":string};
            [HTTPTool POSTForm:[NSString stringWithFormat:@"%@order/pre-confer-order",BaseUrl] para:dic success:^(BOOL isSuccess, id responseObject) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                if (isSuccess) {
                    AddressModel * addressModel = [AddressModel new];
                    [addressModel setValuesForKeysWithDictionary:responseObject[@"data"][@"address"]];
                    NSMutableArray * array = [NSMutableArray array];
                    for (int i = 0; i < [responseObject[@"data"][@"order_detail"] count]; i ++) {
                        OrderDetailModel * model = [OrderDetailModel new];
                        [model setValuesForKeysWithDictionary:responseObject[@"data"][@"order_detail"][i]];
                        [array addObject:model];
                    }
                    ConfirmOrderController * vc = [[ConfirmOrderController alloc]init];
                    vc.addressModel = addressModel;
                    vc.reKey = responseObject[@"data"][@"order_info_redis_key"];
                    vc.orderArray = array;
                    vc.goodsSum = responseObject[@"data"][@"goods_sum"];
                    vc.totalMoney = responseObject[@"data"][@"total_price_format"];
                    vc.farePrice = responseObject[@"data"][@"fare_price_format"];
                    vc.dict = dict;
                    vc.addressCouponKey = responseObject[@"data"][@"goods_redis_key"];
                    if ([responseObject[@"data"][@"coupon"] count] > 0) {
                        OrderTicketModel * model = [[OrderTicketModel alloc]init];
                        [model setValuesForKeysWithDictionary:responseObject[@"data"][@"coupon"]];
                        vc.ticketModel = model;
                    }
                    BaseNavigationController * VC = [[BaseNavigationController alloc]initWithRootViewController:vc];
                    [weakSelf.navigationController presentViewController:VC animated:YES completion:nil];
                    
                }
            } failure:^(NSError *error) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            }];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

-(void)setUI
{
    self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 48 - 64 - 50) style:(UITableViewStylePlain)];
    [self.view addSubview:self.tableview];
    [self.tableview registerNib:[UINib nibWithNibName:@"CartCell" bundle:nil] forCellReuseIdentifier:@"CartCell"];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestData)];
    [self.tableview.mj_header beginRefreshing];
    self.tableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestMoreData)];
}

- (void)requestData
{
    self.index = 1;
    [self requestMoreData];
}

- (void)requestMoreData
{
    if (!self.isLogin) {
        [MBProgressHUD showError:@"未登录"];
        [self endRefresh];
        return;
    }else{
        self.tableview.editing = NO;
        NSDictionary * dict = @{@"token":self.userToken,@"page":[NSString stringWithFormat:@"%ld",self.index]};
        [HTTPTool POSTForm:[NSString stringWithFormat:@"%@/cart/index",BaseUrl] para:dict success:^(BOOL isSuccess, id responseObject) {
            if (isSuccess) {
                if (self.index == 1) {
                    self.dataArray = [NSMutableArray array];
                }
                if (self.index == 1 && [[responseObject objectForKey:@"data"] count] == 0) {  //如果是第一页 还没有数据的话  显示空视图
                    self.rightBtn.hidden = YES;
                    self.tableview.editing = NO;
                    [self.view addSubview:self.emptyView];
                }else
                {
                    [self initToolBar];
                    [self.rightBtn setTitle:@"编辑" forState:(UIControlStateNormal)];
                    [self.emptyView removeFromSuperview];    // 如果不是第一页并且空数据  移除空白视图
                    for (int i = 0; i < [responseObject[@"data"] count]; i ++) {
                        CartModel * model = [[CartModel alloc]init];
                        [model setValuesForKeysWithDictionary:responseObject[@"data"][i]];
                        [self.dataArray addObject:model];
                    }
                }
                if ([responseObject[@"hasmore"] integerValue] == 0) {
                    [self.tableview.mj_footer endRefreshingWithNoMoreData];
                }
                self.index += 1;
                [self.tableview reloadData];
            }
            [self endRefresh];
        } failure:^(NSError *error) {
            [self endRefresh];
        }];
    }
}

- (void)endRefresh
{
    if (self.tableview.mj_header.isRefreshing) {
        [self.tableview.mj_header endRefreshing];
    }else
    {
        [self.tableview.mj_footer endRefreshing];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    CartModel * model = self.dataArray[indexPath.row];
    model.isSelected = YES;
    [self deleteGoods];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CartCell * cell = [tableView dequeueReusableCellWithIdentifier:@"CartCell" forIndexPath:indexPath];
    [cell bindDataWithModel:self.dataArray[indexPath.row]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    CartModel * model = self.dataArray[indexPath.row];
    cell.selectedBlock = ^(BOOL isSelectedCell) {
        CartModel * model = self.dataArray[indexPath.row];
        if (isSelectedCell) {
            self.totalMonry = [model.price_coupon floatValue] * [model.goods_number integerValue] + self.totalMonry;
            model.isSelected = isSelectedCell;
            NSInteger times = 0;
            for (int i = 0; i < self.dataArray.count; i ++) {
                CartModel * model = self.dataArray[i];
                if (model.isSelected == YES) {
                    times += 1;
                }
                if (self.dataArray.count == times) {
                    self.toolBar.selectAllBtn.selected = YES;
                }
            }
        }else
        {
            self.totalMonry = self.totalMonry - [model.price_coupon floatValue] * [model.goods_number integerValue];
            model.isSelected = isSelectedCell;
            for (int i = 0; i < self.dataArray.count; i ++) {
                CartModel * model = self.dataArray[i];
                for (int i = 0; i < self.dataArray.count; i ++) {
                    if (model.isSelected == NO) {
                        self.toolBar.selectAllBtn.selected = NO;
                    }
                }
            }
        }
        self.toolBar.pirceLabel.text = [NSString stringWithFormat:@"¥:%.2f",self.totalMonry];
    };
    
    cell.counterView.addBlock = ^(UITextField *textField) {
        if ([textField.text integerValue] + 1 > 200) {
            [MBProgressHUD showMessage:@"不能再多了"];
        }else
        {
            [self changeGoodsNumWithModel:model isAdd:YES andChangeTextField:textField];
        }
    };
    cell.counterView.subBlock = ^(UITextField *textField) {
        if ( [textField.text integerValue] - 1 < 1){
            [MBProgressHUD showError:@"不能再少了"];
        }else
        {
            [self changeGoodsNumWithModel:model isAdd:NO andChangeTextField:textField];
        }
    };
    return cell;
}

-(void)changeGoodsNumWithModel:(CartModel *)model isAdd:(BOOL)isAdd andChangeTextField:(UITextField *)textField
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString * goodsNum = nil;
    if (isAdd) {
        goodsNum = [NSString stringWithFormat:@"%ld",[textField.text integerValue] + 1];
    }else
    {
        goodsNum = [NSString stringWithFormat:@"%ld",[textField.text integerValue] - 1];
    }
    NSDictionary * dict = @{@"token":self.userToken,@"cart_id":model.cart_id,@"goods_number":goodsNum};
    [HTTPTool POSTForm:[NSString stringWithFormat:@"%@cart/goods-number",BaseUrl] para:dict success:^(BOOL isSuccess, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (isSuccess) {
            dispatch_async(dispatch_get_main_queue(), ^{
                textField.text = goodsNum;
            });
            model.goods_number = goodsNum;
            if (model.isSelected) {
                if (isAdd) {
                    self.totalMonry += [model.price_coupon floatValue];
                }else
                {
                    self.totalMonry -= [model.price_coupon floatValue];
                }
                self.toolBar.pirceLabel.text = [NSString stringWithFormat:@"¥:%.2f",self.totalMonry];
            }
            [self.tableview reloadData];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 115;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 115;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"reload" object:nil];
}

-(ToolBar *)toolBar
{
    if (!_toolBar) {
        _toolBar = [[[NSBundle mainBundle] loadNibNamed:@"ToolBar" owner:self options:nil] lastObject];
        self.totalMonry = 0;
        [self.view addSubview:self.toolBar];
    }
    return _toolBar;
}

-(EmptyView *)emptyView
{
    if (!_emptyView) {
        _emptyView = [[[NSBundle mainBundle] loadNibNamed:@"EmptyView" owner:self options:nil] lastObject];
        _emptyView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - 44 - 64);
    }
    return _emptyView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
